﻿using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using System.Collections.Generic;
using xuni;

namespace xres
{


    /// <summary>
    /// 所有文件的版本信息
    /// </summary>
    public class Versions 
    {
        public const string File_Name = "Versions.bin";


        public static Versions CreateFromString(string str)
        {
            var v = new Versions();

            using (var sr = new StringReader(str))
            {
                v.ParseLines(sr);
            }

            return v;
        }


        public static Versions CreateFromFile(string path)
        {
            var v = new Versions();

            using (var sr = new StreamReader(path, Encoding.UTF8))
            {
                v.ParseLines(sr);
            }

            return v;
        }


        public static void WriteOut(Versions v, string path)
        {
            using (var sw = new StreamWriter(path, false, Encoding.UTF8)) //确保no bom
            {
                var sb = xuni.StringUtils.Builder;

                sw.WriteLine(v.resVersion); //第1行版本号

                foreach (var entry in v.files)
                {
                    var fv = entry.Value;

                    var line = sb.Append(fv.path)
                        .Append('|').Append(fv.len)
                        .Append('|').Append(fv.crc)
                        .Append('|').Append(fv.offset)
                        .BuildString();

                    sw.WriteLine(line);
                    if (false) Debug.Log($"line: {line}");
                }
            }
        }



        public int resVersion = -1;

        public readonly Dictionary<string, FileVersion> files = new Dictionary<string, FileVersion>();


        void ParseLines(TextReader tr)
        {
            var line = "";
            var lineNum = 1;

            while (null != (line = tr.ReadLine()))
            {
                if (1 == lineNum)
                {
                    var c = line[0];
                    if (c < 48 || c > 57)
                    {
                        Debug.Log($"file content has BOM");
                        line = xuni.StringUtils.Builder.Append(line).Remove(0, 1).BuildString();
                    }

                    resVersion = int.Parse(line);
                }
                else
                {
                    var fv = FileVersion.Parse(line);
                    files.Add(fv.path, fv);
                }
                ++lineNum;
            }
            if (false) Debug.Log($"lineNum: {lineNum}");
        }

    } //end of class


}